const Service = require('egg').Service;

class ClassesService extends Service {
  constructor(ctx) {
    super(ctx);
    this.model = ctx.model.Classes;
    this.studentService = this.service.student;
  }

  async getClasses(param) {
    try {
      const result = await this.model.findAll({ 
        where: {account_id: param.account_id},
        attributes: {
          include: [
            [this.app.Sequelize.literal(`(SELECT COUNT(*) FROM student WHERE student.class_id = classes.class_id)`), 'stu_number']
          ]
        }
      });
      return { data: result };
    } catch (e) {
      return { error: e.message };
    }
  }

  async addClasses(param) {
    const row = {
      account_id: param.account_id,
      class_name: param.class_name,
      grade: param.grade,
      teacher_name: param.teacher_name,
      department: param.department,
      enrollment_year: param.enrollment_year
    };
    try {
      return await this.model.create(row);
    } catch (e) {
      return { error: e.message };
    }
  }

  async updateClasses(param) {
    const option = {
      where: {
        class_id: param.class_id
      }
    }
    const row = {
      class_name: param.class_name,
      grade: param.grade,
      teacher_name: param.teacher_name,
      department: param.department,
      enrollment_year: param.enrollment_year
    };
    try {
      return await this.model.update(row, option);
    } catch (e) {
      return { error: e.message };
    }
  }

  async delClasses(param) {
    const option = {
      where: {
        account_id: param.account_id,
        class_id: param.class_id,
       },
    };
    const stuParam = {
      class_id: param.class_id
    }
    try {
      await this.model.destroy(option);
      return await this.studentService.delStudent(stuParam);
    } catch (e) {
      return { error: e.message };
    }
  }
}

module.exports = ClassesService;
